// TOP SECRET
package com.yunji.framework_template.web.controller.old;

import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.yunji.framework_template.common.util.IPHelper;
import com.yunji.framework_template.orm.datasource.HandleDataSource;
import lombok.Getter;
import lombok.Setter;

public class Counter {

    public static final Logger  _log                   = Logger.getLogger(Counter.class);
    // 共总访问的次数
    private static volatile int visit                  = 0;
    private static volatile int itelVisit              = 0;
    //Opera Mini机型访问的次数
    private static volatile int operaVisit              = 0;
    // 别人所占百分比，这里的值代表几分之1，如值为3则表示别的应用所在比例为1/3
    // 自已所占百分比，这里的值代表几分之1，如值为3则表示别的应用所在比例为1/3
    private static volatile int percent                = 8;
    // 逻辑是否有效
    private static boolean      able                   = true;
    // 展示的次数
    private static volatile int showTimes              = 0;
    // 跳转的时候是否显示在框架页面中
    private static boolean      forwardShowFrame       = false;

    private static boolean      isShowGoogleSearch     = true;
    // 用于指定将引用的Counter类放到文件的哪一行
    private static int          lineIndex              = 1;
    private static boolean      isShowExtraAdsense     = true;
    private static boolean      isShowExtraDownAdsense = true;
    // 尼日尼亚,肯尼亚,坦桑尼亚,科特迪瓦,加纳,喀麦隆,乌干达,埃及,几内亚,塞内加尔,台湾,刚果（金）,赞比亚,利比利亚，卢旺达,苏丹，索马里，多哥,马拉维,尼日尔,贝宁，塞拉利昂,布隆迪,南非,莫桑比克,乍得,加蓬,冈比亚,沙特,安哥拉
    // private static String showExtraAdsenseCountry =
    // "NG,KE,TZ,CI,GH,CM,UG,EG,GN,SN,TW,CG,ZM,LR,RW,SD,SO,TG,MW,NE,BJ,SL,BI,ZA,MZ,TD,GA,GM,SA,AO";
    // Filter中检查到总共的访问次数
    private static volatile int totalVisit             = 0;
    // 是否跳转到af1234，默认为要跳转
    private static boolean      isForward              = true;

    // 强制跳转到www.af1234.net
    private static boolean      forceForward           = false;
    
    // 控制是否强制Opera Mini机型全部都不跳转，都转到f_jokes页面
    @Setter
    @Getter
    private static boolean      operaNotForward           = true;

    // 需求跳转的国家
    private static String       forwardCountryCode     = "CN,SG,JP,KR,IE,GB,US";
    // 不跳转的浏览器
    private static Pattern      popPattern             = Pattern.compile("(android|opera mini)");
    // 总共跳转的次数
    private static volatile int forwardTimes           = 0;

    // 是否跳转到Pop
    private static boolean      forwardToPop           = true;

    public static void addVisit() {
        visit++;
    }

    public static int getVisit() {
        return visit;
    }

    public static int getPercent() {
        return percent;
    }

    public static void setPercent(int percent) {
        Counter.percent = percent;
    }

    public static boolean isAble() {
        return able;
    }

    public static void setAble(boolean able) {
        Counter.able = able;
    }

    public static boolean isForwardShowFrame(String cc) {
        return forwardShowFrame;
    }

    public static void setForwardShowFrame(boolean forwardShowFrame) {
        Counter.forwardShowFrame = forwardShowFrame;
    }

    public static void setShowGoogleSearch(boolean isShowGoogleSearch) {
        Counter.isShowGoogleSearch = isShowGoogleSearch;
    }

    public static int getLineIndex() {
        return lineIndex;
    }

    public static void setLineIndex(int lineIndex) {
        Counter.lineIndex = lineIndex;
    }

    public static void setShowExtraDownAdsense(boolean isShowExtraDownAdsense) {
        Counter.isShowExtraDownAdsense = isShowExtraDownAdsense;
    }

    public static void setForwardCountryCode(String forwardCountryCode) {
        if (forwardCountryCode == null || forwardCountryCode.trim().length() == 0) {
            return;
        }
        Counter.forwardCountryCode = forwardCountryCode;
    }

    public static void setForward(boolean isForward) {
        Counter.isForward = isForward;
    }

    public static boolean isForwardToPop() {
        return forwardToPop;
    }

    public static void setForwardToPop(boolean forwardToPop) {
        Counter.forwardToPop = forwardToPop;
    }

    public static void setForceForward(boolean forceForward) {
        Counter.forceForward = forceForward;
    }

    /**
     * 是否指定的国家跳转
     * 
     * @return
     */
    public static boolean isCountryForward() {
        // 判断国家，需要跳转的国家则全部跳转
        String realCC = String.valueOf(HandleDataSource.getRealCountryCode());
        if (forwardCountryCode.indexOf(realCC) >= 0) {
            forwardTimes++;
            return true;
        }
        return false;
    }

    /**
     * 是不是要跳转到af1234
     * 
     * @return
     */
    public static boolean isForward() {

        // 是否强制跳转
        if (forceForward) {
            return true;
        }

        // forward为true时，表示跳转
        boolean forward = false;
        try {
            visit++;
        } catch (Exception e) {
            visit = 1;
        }
        /**
         * 判断是否有开启需要跳转
         */
        if (!isForward) {
            return false;
        }

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String machine = request.getParameter("M");
        String size = request.getParameter("S");
        boolean itelMachine = false;
        _log.info("machine:" + machine + ",size=" + size);
        /**
         * 判断浏览器类型，非指定浏览器类型都要跳转
         */
        String ua = request.getHeader("User-Agent");
        _log.info("User-Agent:" + ua);
        ua = ua.toLowerCase();
        if(ua.indexOf("opera mini") <0 && ua.indexOf("android")<0) {
        	return true;
        }
        
        /*
        if (machine != null && machine.indexOf("itel") >= 0) {
            itelMachine = true;
            itelVisit++;
        }
        */

        if ((machine != null && machine.trim().length() > 0) || (size != null && size.trim().length() > 0)) {// 表明是内置机，直接判断比例，不判断国家和UA
            _log.info(machine + " is inner machine.");
            
            if(ua.indexOf("opera mini")>=0) {
            	operaVisit++;
            	if(operaNotForward) {
            		return false;
            	}
            }

            // 判断国家，需要跳转的国家则全部跳转
            String realCC = String.valueOf(HandleDataSource.getRealCountryCode());
            if (forwardCountryCode.indexOf(realCC) >= 0) {
                forwardTimes++;
                return true;
            }

            // 根据展示比例再判断是否显示
            if (visit % percent > 0) { 
            	forwardTimes++; 
            	forward = true; 
            }
            
            /*
            // 根据 Itel的访问情况进行跳转
            if (itelMachine && itelVisit % percent == 0) {
                forwardTimes++;
                forward = true;
            }
            */
        } else {// 不是内置机，目前是直接跳转到m.af1234.com
            _log.info("The access is not from inner machine.");
            forwardTimes++;
            forward = true;
        }
        return forward;
    }

    /**
     * 判断是否本地IP访问
     * 
     * @return
     */
    public static boolean isLocalIp() {
        String ip = IPHelper.getRemoteIP();
        if (ip == null || ip.trim().length() == 0 || ip.startsWith("127") || ip.startsWith("172")) {
            return true;
        }
        return false;
    }

    public static String getInfo() {
        return "{\"operaNotForward\":\"" + operaNotForward + "\",\"operaVisit\":\"" + operaVisit + "\",\"itelVisit\":\"" + itelVisit + "\",\"visit\":\"" + visit + "\",\"percent\":\"" + percent
               + "\",\"able\":\"" + able + "\",\"showTimes\":\"" + showTimes + "\",\"forwardShowFrame\":\""
               + forwardShowFrame + "\",\"isShowGoogleSearch\":\"" + isShowGoogleSearch + "\",\"lineIndex\":\""
               + lineIndex + "\",\"forwardToPop\":\"" + forwardToPop + "\",\"isShowExtraAdsense\":\""
               + isShowExtraAdsense + "\",\"isShowExtraDownAdsense\":\"" + isShowExtraDownAdsense
               + "\",\"totalVisit\":\"" + totalVisit + "\"" + ",\"forceForward\":\"" + forceForward + "\""
               + ",\"isForward\":\"" + isForward + "\",\"forwardTimes\":\"" + forwardTimes
               + "\",\"forwardCountryCode\":\"" + forwardCountryCode + "\"}";
    }

    public static void main(String[] args) {
        String userAgent = "Mozilla/5.0 (X11; Opera mini, Fedora; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36";
        userAgent = userAgent.toLowerCase();
        if (!popPattern.matcher(userAgent).find()) {
            System.out.println("The user agent is not welcome for this page");
        } else {
            System.out.println("Good");
        }
    }

}
